package com.darrenchan.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-04-19 22:47
 */
public class QLint58 {
    public List<List<Integer>> fourSum(int[] numbers, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(numbers == null || numbers.length < 4) {
            return res;
        }

        Arrays.sort(numbers);
        for (int i = 0; i < numbers.length - 3; i++) {
            if(i > 0 && numbers[i] == numbers[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < numbers.length - 2; j++) {
                if(j > i + 1 && numbers[j] == numbers[j - 1]) {
                    continue;
                }
                findTwoNum(numbers, j + 1, numbers.length - 1, numbers[i], numbers[j], target, res);
            }
        }
        return res;
    }

    private void findTwoNum(int[] numbers, int i, int j, int num1, int num2, int target, List<List<Integer>> res) {
        while(i < j) {
            if(numbers[i] + numbers[j] == target - num1 - num2) {
                List<Integer> subarray = new ArrayList<>();
                subarray.add(num1);
                subarray.add(num2);
                subarray.add(numbers[i]);
                subarray.add(numbers[j]);
                res.add(subarray);

                i++;
                j--;
                while(i < j && numbers[i] == numbers[i - 1]) {
                    i++;
                }
                while(i < j && numbers[j] == numbers[j + 1]) {
                    j--;
                }
            } else if(numbers[i] + numbers[j] < target - num1 - num2) {
                i++;
            } else {
                j--;
            }
        }
    }
}
